package com.mmall.service.impl;

import com.mmall.commons.ResponseCode;
import com.mmall.commons.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.pojo.Category;
import com.mmall.service.ICategoryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wgt
 * @date 2018/6/28
 * @project mmall-server
 */
@Service
public class CategoryServiceImpl implements ICategoryService{

    private Logger logger = LoggerFactory.getLogger(CategoryServiceImpl.class);

    @Autowired
    private CategoryMapper categoryMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse addCategory(String categoryName, int parentId) {
        if (StringUtils.isBlank(categoryName)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "categoryName 不能为空");
        }

        Category category = new Category();
        category.setName(categoryName);
        category.setParentId(parentId);

        int rowCount = categoryMapper.insert(category);
        if (rowCount > 0){
            return ServerResponse.createBySuccessMessage("添加商品分类成功");
        }
        return ServerResponse.createByErrorMessage("添加商品分类失败");
    }

    @Override
    public ServerResponse updateCategoryName(Integer categoryId, String categoryName) {
        if (categoryId == null || StringUtils.isBlank(categoryName)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "更新失败分类名失败，请检查参数");
        }

        int rowCount = categoryMapper.updateCategoryName(categoryId, categoryName);
        if (rowCount > 0){
            return ServerResponse.createBySuccessMessage("更新商品分类成功");
        }

        return ServerResponse.createByErrorMessage("更新商品分类名称失败");
    }

    @Override
    public ServerResponse<List<Category>> getCategoryByParentId(int categoryId) {
        List<Category> categoryList = categoryMapper.getCategoryByParentId(categoryId);

        if (CollectionUtils.isEmpty(categoryList)){
            logger.warn("根据categoryId{}未查找到子节点", categoryId);
            ServerResponse.createBySuccess();
        }
        return ServerResponse.createBySuccess(categoryList);
    }

    @Override
    public ServerResponse getDeepCategoryByParentId(int categoryId) {
        List<Integer> categoryList = categoryMapper.getDeepCategoryByParentId(categoryId);

        if (CollectionUtils.isEmpty(categoryList)){
            logger.warn("根据categoryId{}未查找到子节点", categoryId);
            ServerResponse.createBySuccess();
        }
        return ServerResponse.createBySuccess(categoryList);
    }

}
